package com.miao.admin.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.miao.admin.service.AdminRefundService;
import com.miao.admin.service.OperationService;
import com.miao.common.entity.R;
import com.miao.common.entity.pojo.Operation;
import com.miao.common.entity.pojo.Refund;
import com.miao.common.utils.JWTUtil;
import com.miao.websecurity.entity.Admin;
import com.miao.websecurity.service.AdminService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 退货记录表(Refund)表控制层
 *
 * @author makejava
 * @since 2021-02-22 17:48:33
 */
@RestController
@RequestMapping("admin/refund")

public class AdminRefundController {
    /**
     * 服务对象
     */
    @Resource
    private AdminRefundService adminRefundService;
    @Resource
    private AdminService adminService;
    @Resource
    private OperationService operationService;

    @GetMapping("/getAllRefund")
    public R getAllRefund (@RequestHeader (value = "access-token") String token){
        Admin admin = this.decodeToken(token);

        return R.ok(adminRefundService.getAllRefund(Integer.parseInt(admin.getStoreId())));
    }

    @GetMapping("/getRefundInfo")
    public R RefundInfo (String rId){
        return R.ok(adminRefundService.getRefundInfo(rId));
    }

    @GetMapping("/chgRefundState")
    public R chgRefundState (String rId,int state,String des,@RequestHeader (value = "access-token") String token){

        if (adminRefundService.chgRefundState(rId, state)){
            Admin admin = this.decodeToken(token);
            Operation operation = new Operation();
            Refund refund = adminRefundService.getById(rId);

            operation.setOrderId(refund.getOrderId());
            operation.setOperationTime(new Date());
            operation.setRefId(rId);
            operation.setAdminId(admin.getAdminId());
            if (state==2) {
                operation.setOperationDes("审核通过["+admin.getAdminName()+"]");

            }else if (state==3){
                operation.setOperationDes("服务完成["+admin.getAdminName()+"]");
            }else if (state==4){
                operation.setOperationDes("审核未通过："+des+"["+admin.getAdminName()+"]");
            }

            this.operationService.save(operation);

            return R.ok("状态更新成功");

        }

        return R.error("状态更新失败");

    }
    @GetMapping("/getOpLog")
    public R getOpLog(String rId){

        return R.ok(this.operationService.list(new QueryWrapper<Operation>().eq("ref_id",rId)));

    }





    /**
     * 解析Token
     * @param token
     * @return
     */
    private Admin decodeToken(String token) {

        String s = JWTUtil.analysisToken(token);
        Map map = JSON.parseObject(s, Map.class);
        Admin admin = this.adminService.getById(map.get("adminId").toString()); //1平台 0店铺

        return admin;
    }



}